package org.sanm.domain.category;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.val;
import org.sanm.common.Result;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
@Tag(name = "类别管理", description = "类别管理")
public class CategoryController {

    @PostMapping("add")
    @Operation(summary = "添加类别", description = "添加类别")
    public Result<Category> add(@RequestBody Category category){
        Db.save(category);
        return Result.success(category);
    }

    @PutMapping("update")
    @Operation(summary = "修改类别", description = "修改类别")
    public Result update(@RequestBody Category category){
        Db.updateById(category);
        return Result.success("修改成功");
    }

    @DeleteMapping("delete/{id}")
    @Operation(summary = "删除类别", description = "删除类别")
    public Result delete(@PathVariable("id") Integer id){
        Db.removeById(id, Category.class);
        return Result.success("删除成功");
    }

    @GetMapping("detail/{id}")
    @Operation(summary = "根据id查询类别", description = "根据id查询类别")
    public Result<Category> getDetail(@PathVariable("id") Integer id){
        val category = Db.getById(id, Category.class);
        return Result.success(category);
    }

    @GetMapping("ids")
    @Operation(summary = "根据多个id查询类别", description = "根据多个id查询类别")
    public Result<List<Category>> getByIds(@RequestParam("ids") List<Integer> ids){
        List<Category> list = Db.lambdaQuery(Category.class).in(Category::getId, ids).list();
        return Result.success(list);
    }

    @GetMapping("list")
    @Operation(summary = "分页查询类别", description = "分页查询类别")
    public Result<Page<Category>> page(
            @RequestParam("pageNum") Integer pageNum,
            @RequestParam("pageSize") Integer pageSize,
            @RequestParam(value = "name", required = false) String name
    ){
        Page<Category> page = Page.of(pageNum, pageSize);
        Page<Category> page1 = Db.lambdaQuery(Category.class)
                .like(name != null, Category::getName, name)
                .page(page);
        return Result.success(page);
    }
}
